/*
 * color.cpp
 *
 *  Created on: Apr 24, 2013
 *      Author: filipe
 */
#include <math.h>
#include <stdio.h>
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/nonfree/nonfree.hpp"
#include <vector>

using namespace cv;
using namespace std;

vector<Scalar> objects;
vector<Scalar> object_colors;

int main(int argc, char** argv)
{
	if (argc < 2)
	{
		printf("\nUse %s <img>\n", argv[0]);
		exit(-1);
	}

	srand(time(NULL));

	Mat img = imread(argv[1], CV_LOAD_IMAGE_COLOR);
	Mat out(img);

    if(img.empty())
    {
        printf("Can't read one of the images\n");
        return -1;
    }

    for (int i = 0; i < img.rows; i++)
    {
    	for (int j = 0; j < img.cols; j++)
    	{
    		printf("i = %06d\tj = %06d\n", i, j);

    		Scalar c = img.at<Scalar>(i, j);
    		int found = 0;

    		for (uint k = 0; k < objects.size(); k++)
    		{
    			double color_dist = sqrt(
    				pow(c.val[0] - objects[k].val[0], 2) +
    				pow(c.val[1] - objects[k].val[1], 2) +
    				pow(c.val[2] - objects[k].val[2], 2)
    			);

    			if (color_dist < 10)
    			{
    				out.at<Scalar>(i, j) = object_colors[k];
    				found = 1;
    			}
    		}

    		if (!found)
    		{
    			objects.push_back(c);

        		int rand_r = (int) (((double) rand() / (double) RAND_MAX) * 255);
        		int rand_g = (int) (((double) rand() / (double) RAND_MAX) * 255);
        		int rand_b = (int) (((double) rand() / (double) RAND_MAX) * 255);

    			object_colors.push_back(Scalar(rand_b, rand_g, rand_r));
    		}
    	}
    }

    printf("num objects: %ld\n", objects.size());
    return 0;
}



